<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="60px">
      <el-form-item label="学号" prop="studentId">
        <el-input v-model="queryParams.studentId" placeholder="请输入学号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
          <el-option v-for="dict in gender" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="生源地" prop="originPlace">
        <el-select v-model="queryParams.originPlace" placeholder="请选择生源地" clearable>
          <el-option v-for="dict in student_orgin_address" :key="dict.value" :label="dict.label" :value="dict.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="独生" prop="isOnlyChild">
        <el-select v-model="queryParams.isOnlyChild" placeholder="请选择独生信息" clearable>
          <el-option v-for="dict in onlyChildOptions" :key="dict.value" :label="dict.label" :value="dict.label" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['students:students:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['students:students:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['students:students:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['students:students:export']">导出</el-button>
        <el-button type="warning" plain icon="upload" @click="handleImport"
          v-hasPermi="['students:students:add']">导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="60" />
      <el-table-column label="学号" align="center" prop="studentId" />
      <el-table-column label="姓名" prop="name" align="center" />
      <el-table-column label="班级" prop="studentclass" align="center" width="60" />
      <el-table-column label="性别" prop="gender" align="center" width="60">
        <template #default="scope">
          <dict-tag :options="gender" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="出生日期" prop="birthDate" align="center">
        <template #default="scope">
          <span>{{ parseTime(scope.row.birthDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生源地" prop="originPlace" align="center" />
      <el-table-column label="独生子女" align="center" prop="isOnlyChild" />
      <el-table-column label="任职情况" prop="cadrePosition" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)"
            v-hasPermi="['students:students:edit']">修改</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)"
            v-hasPermi="['students:students:remove']">删除</el-button>
          <el-button link type="primary" @click="handlequeryAward(scope.row)"
            v-hasPermi="['awards:awards:query']">获奖查询</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改学生基本信息管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="studentsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学号" :disabled="disabledOr" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="班级" prop="studentclass">
          <el-select v-model="form.studentclass" placeholder="请选择班级" clearable>
            <el-option v-for="dict in class_name" :key="dict.value" :label="dict.label" :value="dict.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="学校" prop="scchoolMeaasge">
          <el-select v-model="form.scchoolMeaasge" placeholder="请选择班级" clearable>
            <el-option v-for="dict in school_name" :key="dict.value" :label="dict.label" :value="dict.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="入学年份" prop="yearAdmission">
          <el-input v-model="form.yearAdmission" placeholder="请输入入学年份" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option v-for="dict in gender" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker clearable v-model="form.birthDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="生源地" prop="originPlace">
          <el-select v-model="form.originPlace" placeholder="请选择生源地">
            <el-option v-for="dict in student_orgin_address" :key="dict.value" :label="dict.label"
              :value="dict.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="独生子女" prop="isOnlyChild">
          <el-select v-model="form.isOnlyChild" placeholder="请选择生源地">
            <el-option v-for="dict in onlyChildOptions" :key="dict.value" :label="dict.label"
              :value="dict.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任职情况" prop="cadrePosition">
          <el-input v-model="form.cadrePosition" placeholder="请输入任职情况" />
        </el-form-item>
      </el-form>
      <span style="top: 10px;" v-if="type == 0">新增用户默认密码为123456</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 获奖信息管理对话框 -->
    <el-dialog title="获奖信息" v-model="awardloading" width="700px" append-to-body>
      <el-table :data="awardsList" style="height: 500px;">
        <el-table-column label="获奖名称" align="center" prop="awardName" width="160" />
        <el-table-column label="等级" align="center" prop="awardLevel" width="100">
          <template #default="scope">
            <dict-tag :options="award_lever" :value="scope.row.awardLevel" />
          </template>
        </el-table-column>
        <el-table-column label="获奖日期" align="center" prop="awardDate" width="140">
          <template #default="scope">
            <span>{{ parseTime(scope.row.awardDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="图片" align="center" prop="awardPhotoPath">
          <template #default="scope">
            <image-preview :src="scope.row.awardPhotoPath" :width="80" :height="80" />
          </template>
        </el-table-column>
      </el-table>

    </el-dialog>
    <!-- 上传文件 -->
    <el-dialog title="上传文件" v-model="excelopen" width="400px" append-to-body>
      <el-upload ref="uploadRef" class="upload-demo" :action="uploadImgUrl" :headers="headers"
        :on-error="handleUploadError" :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload"
        :auto-upload="false">
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button class="ml-3" type="success" @click="submitUpload">
          上传文件
        </el-button>
        <template #tip>
          <div class="el-upload__tip">
            只能上传xlx文件
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup name="Students">
import { listStudents, getStudents, delStudents, addStudents, updateStudents } from "@/api/students/students";
import UploadUtils from '@/utils/UploadUtils';
const { proxy } = getCurrentInstance();
import { getToken } from "@/utils/auth";
const { student_orgin_address, gender, onlyChildOptions, school_name, grade_name, class_name } = proxy.useDict('student_orgin_address', 'gender', 'onlyChildOptions', 'school_name', 'grade_name', 'class_name');
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/students/students/importData");
const headers = ref({ Authorization: "Bearer " + getToken() });
const studentsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const type = ref(0)
const disabledOr = ref(true)
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: null,
    name: null,
    studentclass: null,
    grade: null,
    gender: null,
    birthDate: null,
    originPlace: null,
    isOnlyChild: null,
    cadrePosition: null
  },
  rules: {
    studentId: [
      { required: true, message: "学号不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    studentclass: [
      { required: true, message: "班级不能为空", trigger: "blur" }
    ],
    gender: [
      { required: true, message: "性别不能为空", trigger: "change" }
    ],
    yearAdmission: [
      { required: true, message: "入学年份不能为空", trigger: "change" }
    ],
    scchoolMeaasge: [
      { required: true, message: "学校信息不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询学生基本信息管理列表 */
function getList() {
  loading.value = true;
  listStudents(queryParams.value).then(response => {
    studentsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
import { listTeacher } from "@/api/teacher/teacher";
async function getListByTeacher() {
  loading.value = true;
  const data = {
    teacherid: infoName.value
  }
  const result = await listTeacher(data)
  queryParams.value.scchoolMeaasge = result.rows[0].school
  queryParams.value.yearAdmission = result.rows[0].yearAdmission
  queryParams.value.studentclass = result.rows[0].classss

  listStudents(queryParams.value).then(response => {
    studentsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    studentId: null,
    name: null,
    studentclass: null,
    grade: null,
    gender: null,
    birthDate: null,
    originPlace: null,
    isOnlyChild: null,
    cadrePosition: null
  };
  proxy.resetForm("studentsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  disabledOr.value = false;
  reset();
  open.value = true;
  title.value = "添加学生基本信息管理";
  type.value = 0
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getStudents(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改学生基本信息管理";
    type.value = 1
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["studentsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateStudents(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 默认密码
        form.value.password = '123456'
        addStudents(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除学生基本信息管理编号为"' + _ids + '"的数据项？').then(function () {
    return delStudents(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('students/students/export', {
    ...queryParams.value
  }, `students_${new Date().getTime()}.xlsx`)
}

const infoName = ref('')
// 查询基本信息
import { getInfo } from "@/api/login";
// 获取当前用户信息
async function fetchInfo() {
  try {
    const result = await getInfo(); // 等待函数解析完成    
    infoName.value = result.user.userName;
    if (result.roles[0] == "admin") {
      getList();
    } else if (result.roles[0] == 'teacher') {
      getListByTeacher()
    }

  } catch (error) {
    console.error(error);
  }
}
fetchInfo()

/*
查询获奖信息
*/
const { award_lever } = proxy.useDict('award_lever');
const awardloading = ref(false);
import { listAwards } from "@/api/awards/awards";
import { ref } from "vue";
const awardsList = ref([]);
function handlequeryAward(row) {
  awardloading.value = true;
  const data = {
    studentId: row.studentId
  }
  listAwards(data).then(response => {
    awardsList.value = response.rows
  })
}

// 文件上传导入
// 学生信息导入功能 导入excel
const props = defineProps({
  modelValue: [String, Object, Array],
  fileSize: {
    type: Number,
    default: 1,
  },
  fileType: {
    type: Array,
    default: () => ["xls", "xlsx"],
  }
});

const { excelopen, uploadRef, handleImport, submitUpload, handleUploadError, handleBeforeUpload, handleUploadSuccess } = UploadUtils(props, proxy, getList);

</script>
